package com.roche.spring02.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        /**
         * 首页谁都可以访问
         * page需要user角色才能访问
         */

        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/index").permitAll()
                .antMatchers("/user/*").permitAll()
                .antMatchers("/page/*").hasRole("USER")
                .antMatchers("/info/*").hasAnyRole("USER","YOUKE");

        //开启了spring内置的登录页面
        http.formLogin().loginPage("/user/login").loginProcessingUrl("/authentication/form");

        //配置可注销
        http.logout().logoutSuccessUrl("/index");
        http.csrf().disable();
        http.rememberMe();
    }

    /**
     * 配置了一个从内存中读取用户的方式，后续应该是从数据库中读
     * USER 用户角色可以访问page页面
     * YOUkE 用户则不能访问page页面
     *
     * 使用了密码解码器：passwordEncoder 可以换成其他的解码器
     *
     */

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {


        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("roche")
                .password(new BCryptPasswordEncoder().encode("123456")).roles("USER")
                .and()
                .withUser("youke")
                .password(new BCryptPasswordEncoder().encode("123456")).roles("YOUKE");

    }
}
